//
//  QBController.swift
//  mggz
//
//  Created by Apple on 2018/4/25.
//  Copyright © 2018年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import SVProgressHUD
import MJRefresh
import RxCocoa
import RxSwift

class QBController: UIViewController {

    @IBOutlet weak var tableview: UITableView!
    @IBOutlet weak var money: UILabel!
    @IBOutlet weak var line: UIView!
    var emptyview:EmptyView?
    
    var datavariable:PublishSubject<[QBItemDetail]> = PublishSubject()
    var datalist = [QBItemDetail]()
    
    var tablefoot:MJRefreshBackNormalFooter?
    
    var params = [String:Any]()
    var page = 1
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.tableview.separatorStyle = .singleLine
        self.tableview.register(UINib(nibName: "QbItemView", bundle: nil), forCellReuseIdentifier: "cell")
        self.tableview.rowHeight = 70
        self.tableview.tableFooterView = UIView(frame: CGRect.zero)

        self.datavariable.asObservable().bind(to: self.tableview.rx.items){
            (_,row,element) in
            let cell = self.tableview.dequeueReusableCell(withIdentifier: "cell", for: IndexPath(row : row, section : 0)) as! QbItemView
            cell.itemData = element
            cell.selectionStyle = .none
            return cell
        }
        let tablehead = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(refresh))
        tablehead?.stateLabel.isHidden = true
        self.tableview.mj_header = tablehead
        
        self.tablefoot = MJRefreshBackNormalFooter(refreshingTarget: self, refreshingAction: #selector(loadMore))
        self.tablefoot?.stateLabel.isHidden = true
        self.tableview.mj_footer = tablefoot
        
        SVProgressHUD.setDefaultMaskType(.clear)
        getTotalDetail()
        SVProgressHUD.show(withStatus: "正在加载")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    @objc func refresh(){
        self.page = 1
        self.tablefoot?.stateLabel.isHidden = true
        self.getDataList()
    }
    
    @objc func loadMore(){
        self.page += 1
        self.tablefoot?.stateLabel.isHidden = true
        self.getDataList()
    }
    
    
    
    func getTotalDetail(){
        
        var totalParams = [String:Any]()
        MNetHttp.sharedInstance.postSingle(API_CALL_METHOD, method: .QIANBAOList, params: &totalParams, type: QianBao.self, success: { (bean,_) in
            
            guard let tt = bean as? QianBao else{
                return
            }
            if tt.Result == nil || tt.Result == 0{
                self.money.text = "0.00"
            }else{
                self.money.text = "\((tt.Result)!)"
            }
            self.getDataList()
            
        }) { (error) in
            switch error{
            case .DATAERROR:
                self.addHttpErrorView("数据异常")
                break;
            case .DATAFAIL:
                self.addHttpErrorView("数据解析异常")
                break;
            case .HTTPERROR:
                self.addHttpErrorView("网络异常")
                break;
            case .StateFail(let obj):
                guard let data = obj as? [String:Any] else{
                    self.addEmptyView("网络异常")
                    return
                }
                self.addEmptyView(data["Msg"] as? String ?? "")
                break
            }
        }
    }
    
    func getDataList(){
        params["pageSize"] = "\(PageSize)"
        params["pageIndex"] = "\(self.page)"
        MNetHttp.sharedInstance.postSingle(API_CALL_METHOD, method: .QIANBAOListDetail, params: &params, type: QBItem.self, success: { (bean,_) in
            guard let d = bean as? QBItem else{
                self.addEmptyView("数据异常")
                return
            }
            if self.page == 1{
                self.datalist.removeAll()
                self.tableview.mj_header.endRefreshing()
                self.tableview.mj_footer.endRefreshing()
                if d.Result?.SalaryList?.count == 0{
                    self.addEmptyView()
                }
                
            }else{
                if (d.Result?.SalaryList?.count ?? 0) < PageSize{
                    self.tablefoot?.stateLabel.isHidden = false
                    self.tableview.mj_footer.endRefreshingWithNoMoreData()
                    //SVProgressHUD.showInfo(withStatus: "暂无更多数据")
                }else{
                    self.tableview.mj_footer.endRefreshing()
                }
                
            }
            self.datalist.append(contentsOf: (d.Result?.SalaryList)!)
            self.datavariable.onNext(self.datalist)
            SVProgressHUD.dismiss()
        }) { (error) in
            
            
            SVProgressHUD.dismiss()
            
            switch error{
            case .DATAERROR:
                self.addEmptyView("数据异常")
                break;
            case .DATAFAIL:
                self.addEmptyView("数据解析异常")
                break;
            case .HTTPERROR:
                self.addEmptyView("网络异常")
                break;
            case .StateFail(let obj):
                guard let data = obj as? [String:Any] else{
                    self.addEmptyView("网络异常")
                    return
                }
                self.addEmptyView(data["Msg"] as? String ?? "")
                break
            }
        }
    }
    
    func addEmptyView(_ status:String = "暂无钱包明细"){
        
        if self.emptyview != nil{
            self.emptyview?.removeFromSuperview()
            self.emptyview = nil
        }
        
        self.emptyview = EmptyView(frame: CGRect.zero, _title: status,_top:Float(SCREEN_HEIGHT/4))
        self.view.addSubview(self.emptyview!)
        self.emptyview?.snp.updateConstraints({ (make) in
            make.top.equalTo(self.line.snp.bottom)
            make.left.equalTo(self.view.snp.left)
            make.right.equalTo(self.view.snp.right)
            make.bottom.equalTo(self.view.snp.bottom)
        })
    }
    
    func addHttpErrorView(_ status:String){
        if self.emptyview != nil{
            self.emptyview?.removeFromSuperview()
            self.emptyview = nil
        }
        
        self.emptyview = EmptyView(frame: CGRect.zero, _title: status,_top:Float(SCREEN_HEIGHT/5))
        self.view.addSubview(self.emptyview!)
        self.emptyview?.snp.updateConstraints({ (make) in
            make.top.equalTo(self.view.snp.top)
            make.left.equalTo(self.view.snp.left)
            make.right.equalTo(self.view.snp.right)
            make.bottom.equalTo(self.view.snp.bottom)
        })
        
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
